package com.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.biz.*;
import com.controller.backend.BaseController;
import com.core.BizException;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.bo.PayData;
import com.entity.cond.BaseCond;
import com.entity.model.*;
import com.entity.vo.BillListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sms.SmsUtil;
import com.util.CalendarUtil;
import com.util.HttpRequest;
import com.util.PayUtil;
import com.util.template.Template;
import com.util.template.TemplateParam;
import com.util.webpage.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.util.CalendarUtil.getNow;
import static com.util.CalendarUtil.getNowStr2;
import static com.util.CalendarUtil.getToday;

/**
 * Created by jc on 2019/11/16.
 */
@RestController("apiBillController")
@RequestMapping("/api/bill")
public class BillController extends BaseController<Bill> {
    @Autowired
    private BillBiz billBiz;

    @Autowired
    private BillRefundBiz billRefundBiz;

    @Autowired
    private HotelPhotoBiz hotelPhotoBiz;

    @Autowired
    private CustomerBiz customerBiz;

    @Autowired
    private HotelBiz hotelBiz;

    @Autowired
    private HotelHomeBiz hotelHomeBiz;

    @Autowired
    private HotelReservationBiz hotelReservationBiz;

    @Autowired
    private SysConfigBiz sysConfigBiz;

    @RequestMapping(value = "/customerBillList")
    public Result customerBillList(BaseCond bcond, Integer customerId, Integer status) throws Exception {
        if (customerId == null) {
            ArrayList list = new ArrayList();
            return ResultGenerator.genSuccessResult(list);
        }
        //用户查询订单 首先将当前用户 状态未过期的订单更新为已过期订单
        Map cond = new HashMap();
        cond.put("customerId", customerId);
        billBiz.delExpiredBillByCustomerId(cond);

        PageHelper.startPage(bcond.getPageNum(), bcond.getPageSize(), false);
        PageHelper.orderBy(bcond.getOrderBy());
        PageData data = new PageData();
        data.put("customerId", customerId);
        data.put("status", status);
        List<BillListVO> billListVO = billBiz.findCustomerBill(data);
        if (billListVO.size() > 0) {
            for (Integer i = 0; i < billListVO.size(); i++) {
                Condition condition = new Condition(HotelPhoto.class);
                condition.orderBy("id").asc();
                condition.createCriteria().andEqualTo("hotelId", billListVO.get(i).getHotelId());
                List<HotelPhoto> hotelPhotoList = hotelPhotoBiz.findByCondition(condition);
                if (hotelPhotoList.size() > 0) {
                    billListVO.get(i).setHotelPhoto(hotelPhotoList.get(0).getUrl());
                }

                Date date1 = CalendarUtil.strToDate(getNowStr2() + " 14:00:00");
                Date date2 = billListVO.get(i).getReserveStartTime();
                Integer days = CalendarUtil.daysBetween(date1, date2);
                if (days >= 2) {
                    billListVO.get(i).setIsCancel(0);//允许取消
                } else if (days < 2) {
                    billListVO.get(i).setIsCancel(1);//不允许取消
                }
            }
        }
        return ResultGenerator.genSuccessResult(billListVO);
    }

    @RequestMapping(value = "/customerBillCancel")
    public Result customerBillCancel(@RequestParam Integer billId) {
        Bill bill = billBiz.findById(billId);
        if (bill.getStatus() == 0) {
            bill.setStatus(4);
            billBiz.update(bill);
        } else if (bill.getStatus() == 1) {
            bill.setStatus(4);
            billBiz.update(bill);

            BillRefund billRefund = new BillRefund();
            billRefund.setBillNo(bill.getBillNo());
            billRefund.setBillFee(bill.getBillFee());
            billRefund.setBillId(bill.getId());
            billRefund.setHomeId(bill.getHomeId());
            billRefund.setHotelId(bill.getHotelId());
            billRefund.setCustomerId(bill.getCustomerId());
            billRefundBiz.save(billRefund);


            HotelReservation hotelReservation = hotelReservationBiz.findBy("billId", bill.getId());
            hotelReservation.setStatus(3);
            hotelReservationBiz.update(hotelReservation);

            Hotel hotel = hotelBiz.findById(bill.getHotelId());
            HotelHome hotelHome = hotelHomeBiz.findById(bill.getHomeId());
            Customer customer = customerBiz.findById(bill.getCustomerId());

            Template template = new Template();
            template.setTemplate_id("xCT8YoT6YsHyqSRsnILYGgYuVFAMX4QokpZV7QCoyYA");
            template.setTouser(customer.getOpenid());
            template.setPage("pages/tab/index/index");
            List<TemplateParam> paras = new ArrayList<TemplateParam>();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paras.add(new TemplateParam("thing1", hotel.getHotelName()));
            paras.add(new TemplateParam("thing8", hotelHome.getHomeName()));
            paras.add(new TemplateParam("phrase2", "取消成功"));
            paras.add(new TemplateParam("date5", formatter.format(hotelReservation.getReserveStartTime())));
            paras.add(new TemplateParam("date6", formatter.format(hotelReservation.getReserveEndTime())));
            template.setTemplateParamList(paras);
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
            requestUrl = requestUrl.replace("ACCESS_TOKEN", getToken());

            System.out.println(template.toJSON());
            JSONObject jsonResult = JSON.parseObject(PayUtil.httpRequest(requestUrl, "POST", template.toJSON()));
            if (jsonResult != null) {
                System.out.println(jsonResult);
                String errorCode = jsonResult.getString("errcode");
                String errorMessage = jsonResult.getString("errmsg");
                if (errorCode == "0") {
                    System.out.println("Send Success");
                } else {
                    System.out.println("订阅消息发送失败:" + errorCode + "," + errorMessage);
                }
            }

            SmsUtil.cancelBillMsg(customer.getAccount(), hotelReservation.getReserveStartTime(), hotelReservation.getReserveEndTime(), hotel.getHotelName(), hotelHome.getHomeName());

            if (hotelReservation != null) {
                hotelReservation.setStatus(2);
                hotelReservationBiz.update(hotelReservation);

                if (hotelReservation.getReserveEndTime().getTime() >= CalendarUtil.getNow().getTime()) {
                    return billRefundBiz.refund(bill.getId(), billRefund.getId());
                }
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    @RequestMapping(value = "/customerBillDetail")
    public Result customerBillDetail(@RequestParam Integer billId, @RequestParam Integer customerId) throws Exception {
        BillListVO billDetail = billBiz.getBillDetail(billId);

        Date date1 = CalendarUtil.strToDate(getNowStr2() + " 14:00:00");
        Date date2 = billDetail.getReserveStartTime();
        Integer days = CalendarUtil.daysBetween(date1, date2);
        if (days >= 2) {
            billDetail.setIsCancel(0);//允许取消
        } else if (days < 2) {
            billDetail.setIsCancel(1);//不允许取消
        }

        Customer customer = customerBiz.findBy("userId", customerId);

        //用户查询订单 首先将当前用户 状态未过期的订单更新为已过期订单x
        Map cond = new HashMap();
        cond.put("customerId", customerId);
        billBiz.delExpiredBillByCustomerId(cond);

        Condition condition = new Condition(HotelPhoto.class);
        condition.orderBy("id").asc();
        condition.createCriteria().andEqualTo("hotelId", billDetail.getHotelId());
        List<HotelPhoto> hotelPhotoList = hotelPhotoBiz.findByCondition(condition);
        if (hotelPhotoList.size() > 0) {
            billDetail.setHotelPhoto(hotelPhotoList.get(0).getUrl());
        }
        return ResultGenerator.genSuccessResult(billDetail);
    }

    public String getToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        String result = HttpRequest.sendGet(url, "grant_type=client_credential&appid=wx8a5bf19a3b8d5cd3&secret=52c497db3697593faf66936fd7e3f337");
        JSONObject object = JSON.parseObject(result);
        String Access_Token = object.getString("access_token");
        return Access_Token;
    }


    //获取佣金订单列表详情
    @RequestMapping(value = "commissionBillList")
    public Result commissionBillList(BaseCond bcond, @RequestParam Integer customerId, @RequestParam Integer type, @RequestParam Integer status) {
        PageHelper.startPage(bcond.getPageNum(), bcond.getPageSize(), false);
        PageData cond = new PageData();
        cond.put("parentCustomerId", customerId);
        cond.put("type", type);
        cond.put("status", status);
        List<Bill> list = billBiz.commissionBillList(cond);
        PageInfo<Bill> pageInfo = new PageInfo<Bill>(list);
        Integer total = (int) pageInfo.getTotal();
        return ResultGenerator.genSuccessResult(list, total);
    }


    public Customer getAccount(String account) throws BizException {
        Condition cond = new Condition(Customer.class);
        cond.createCriteria().andEqualTo("account", account);
        List<Customer> list = customerBiz.findByCondition(cond);
        return list == null || list.size() == 0 ? null : null;
    }


    @RequestMapping(value = "/getPayFee")
    public Result getPayFee() {
        SysConfig sysConfig = sysConfigBiz.findById(1);
        if (!sysConfig.getBeginDate().equals("") && !sysConfig.getEndDate().equals("") && sysConfig.getActFee() != null && CalendarUtil.strToDate(sysConfig.getBeginDate()).getTime() <= CalendarUtil.getNow().getTime() && CalendarUtil.strToDate(sysConfig.getEndDate()).getTime() >= CalendarUtil.getNow().getTime()) {
            return ResultGenerator.genSuccessResult(sysConfig.getActFee());
        } else {
            return ResultGenerator.genSuccessResult(899.00);
        }
    }
}
